package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmscommon.service.ISysLogService;
import com.sunda.spmsorder.dto.CategoryCreateDTO;
import com.sunda.spmsorder.dto.CategoryUpdateDTO;
import com.sunda.spmsorder.entity.MaterialCategory;
import com.sunda.spmsorder.entity.MaterialSpms;
import com.sunda.spmsorder.mapper.MaterialCategoryMapper;
import com.sunda.spmsorder.mapper.MaterialSpmsMapper;
import com.sunda.spmsorder.service.IMaterialCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 物料分类表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2020-11-16
 */
@Slf4j
@Service
public class MaterialCategoryServiceImpl extends ServiceImpl<MaterialCategoryMapper, MaterialCategory> implements IMaterialCategoryService {

    @Autowired
    MaterialCategoryMapper materialCategoryMapper;

    @Autowired
    MaterialSpmsMapper materialSpmsMapper;

    @Autowired
    ISysLogService iSysLogService;

    @Override
    public List<Map<String, Object>> getMaterialCategoryList() {
        return materialCategoryMapper.getMaterialCategoryList();
    }

    @Override
    public List<Map<String, Object>> getMaterialCategoryDtlList() {
        return materialCategoryMapper.getMaterialCategoryDtlList();
    }

    @Override
    public Map<String, Object> getCategoryMaterial(String categoryId, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<Map<String, Object>> mapList = materialCategoryMapper.getCategoryMaterial(categoryId);
        PageInfo<Map<String, Object>> pageData = new PageInfo<>(mapList);
        HashMap<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("records", pageData.getList());
        pageInfo.put("total", pageData.getTotal());
        pageInfo.put("size", pageData.getSize());
        pageInfo.put("current", pageData.getPageNum());
        pageInfo.put("pages", pageData.getPages());
        return pageInfo;
    }

    /**
     * {
     * 	"materialSpmsList": [{
     * 		"categoryId": "100608",
     * 		"materialNo": "170001240"
     *        }, {
     * 		"categoryId": "100608",
     * 		"materialNo": "170001241"
     *    }]
     * }
     * @param doc
     * @param userId
     * @return
     */
    @Override
    public ResponseResult createCategoryMaterial(JSONObject doc, String userId) {
        try {
            if (!doc.containsKey("materialSpmsList") || doc.getJSONArray("materialSpmsList").size() == 0){
                return ResponseResult.error("请求参数错误");
            }
            JSONArray array = doc.getJSONArray("materialSpmsList");
            for(int i = 0; i < array.size(); i ++){
                MaterialSpms materialSpms = new MaterialSpms();
                materialSpms.setCategoryId(Integer.parseInt(array.getJSONObject(i).getString("categoryId")));
                materialSpms.setMaterialNo(array.getJSONObject(i).getString("materialNo"));
                if (materialSpmsMapper.selectOne(new QueryWrapper<MaterialSpms>()
                        .eq("CATEGORY_ID", materialSpms.getCategoryId())
                        .eq("MATERIAL_NO", materialSpms.getMaterialNo())) != null){
                    /** 存在则更新 */
                    materialSpmsMapper.update(materialSpms, new QueryWrapper<MaterialSpms>()
                            .eq("CATEGORY_ID", materialSpms.getCategoryId())
                            .eq("MATERIAL_NO", materialSpms.getMaterialNo()));
                }else{
                    /** 不存在则新增数据 */
                    materialSpms.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                    materialSpmsMapper.insert(materialSpms);
                }
            }
            iSysLogService.addSysLog("1", "目录维护", "修改", userId, "",
                    "createCategoryMaterial", "materialCategory/createCategoryMaterial/",
                    "POST", "", array.toJSONString(), "", "");
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error();
        }
    }

    /***
     * 	["e2eeae29cee14459a03ad4e8d69cf52a", "407e325fa473460fa7e321ba1985607c"]
     *
     * @param doc
     * @return
     */
    @Override
    public ResponseResult deleteCategoryMaterial(String [] doc, String userId) {
        try {
            if (doc.length == 0){
                return ResponseResult.error();
            }
            for (String uuid : doc){
                materialSpmsMapper.delete(new QueryWrapper<MaterialSpms>().eq("UUID", uuid));
            }
            iSysLogService.addSysLog("1", "目录维护", "删除", userId, "",
                    "deleteCategoryMaterial", "materialCategory/deleteCategoryMaterial/",
                    "POST", "", doc.toString(), "", "");
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error();
        }
    }

    /** 根据用户输入信息 新增 请购商城目录数据； */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult createCategory(CategoryCreateDTO categoryCreateDTO, String userId) {
        try {
            ResponseResult checkResult = checkCreate(categoryCreateDTO);
            if (checkResult.getCode() != 200){
                return checkResult;
            }
            Integer categoryLevel = categoryCreateDTO.getCategoryLevel();
            Integer parentId = categoryCreateDTO.getParentId();
            String categoryName = categoryCreateDTO.getCategoryName();
            String categoryENName = categoryCreateDTO.getCategoryENName();
            Integer categoryRank = categoryCreateDTO.getCategoryRank() == null ? 0 : categoryCreateDTO.getCategoryRank();
            MaterialCategory materialCategory = new MaterialCategory();

            Integer categoryId = generateCategoryId(categoryLevel, parentId);
            //if (categoryId == -1){
            //    return ResponseResult.error("请求参数 categoryLevel:" + categoryLevel + ", parentId:" + parentId + " 对应目录不存在");
            //}
            materialCategory.setCategoryId(categoryId);
            materialCategory.setCategoryLevel(categoryLevel);
            materialCategory.setParentId(parentId);
            materialCategory.setCategoryName(categoryName);
            materialCategory.setCategoryENName(categoryENName);
            materialCategory.setCategoryRank(categoryRank);
            materialCategory.setCreateUserId(userId);
            this.baseMapper.insert(materialCategory);
            return ResponseResult.success().add("materialCategoryList", materialCategoryMapper.getMaterialCategoryDtlList());
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error().add("请求失败", e.getMessage());
        }
    }

    synchronized Integer generateCategoryId(Integer categoryLevel, Integer parentId){
        Integer maxCategoryId = this.baseMapper.getMaxCategoryId(categoryLevel, parentId);
        //if (maxCategoryId == -1){
        //    return -1;
        //}
        if (maxCategoryId == 0){
            if (categoryLevel == 1){
                return 10;
            }
            if (categoryLevel == 2 || categoryLevel == 3){
                maxCategoryId = parentId * 100;
            }
        }
        return maxCategoryId + 1;
    }

    ResponseResult checkCreate(CategoryCreateDTO categoryCreateDTO){
        Integer categoryLevel = categoryCreateDTO.getCategoryLevel();
        if (categoryLevel == null){
            return ResponseResult.error("请求参数错误 categoryLevel 不能为空");
        }
        if (!categoryLevel.equals(1)
                && !categoryLevel.equals(2)
                && !categoryLevel.equals(3)){
            return ResponseResult.error("请求参数 categoryLevel 值非法");
        }
        Integer parentId = categoryCreateDTO.getParentId();
        if (parentId == null){
            return ResponseResult.error("请求参数错误 parentId 不能为空");
        }
        String categoryName = categoryCreateDTO.getCategoryName();
        if (StringUtils.isEmpty(categoryName)){
            return ResponseResult.error("请求参数错误 categoryName 不能为空");
        }
        String categoryENName = categoryCreateDTO.getCategoryENName();
        if (StringUtils.isEmpty(categoryENName)){
            return ResponseResult.error("请求参数错误 categoryENName 不能为空");
        }
        if (categoryLevel.equals(2) || categoryLevel.equals(3)){
            MaterialCategory materialCategory = this.baseMapper.selectOne(new QueryWrapper<MaterialCategory>().eq("CATEGORY_ID", parentId));
            if (materialCategory == null){
                return ResponseResult.error("请求参数 categoryLevel:" + categoryLevel + ", parentId:" + parentId + " 对应目录不存在");
            }
        }
        return ResponseResult.success();
    }

    /** 根据用户输入信息 更新 请购商城目录数据； */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult updateCategory(List<CategoryUpdateDTO> categoryUpdateDTOList, String userId) {
        try {
            ResponseResult checkResult = checkUpdate(categoryUpdateDTOList);
            if (checkResult.getCode() != 200){
                return checkResult;
            }
            for (CategoryUpdateDTO categoryUpdateDTO : categoryUpdateDTOList) {
                Integer categoryId = categoryUpdateDTO.getCategoryId();
                String categoryName = categoryUpdateDTO.getCategoryName();
                String categoryENName = categoryUpdateDTO.getCategoryENName();
                Integer categoryRank = categoryUpdateDTO.getCategoryRank();
                QueryWrapper<MaterialCategory> queryWrapper = new QueryWrapper<MaterialCategory>().eq("CATEGORY_ID", categoryId);
                MaterialCategory materialCategory = this.baseMapper.selectOne(queryWrapper);
                if (StringUtils.isNotEmpty(categoryName)){
                    materialCategory.setCategoryName(categoryName);
                }
                if (StringUtils.isNotEmpty(categoryENName)){
                    materialCategory.setCategoryENName(categoryENName);
                }
                if (categoryRank != null){
                    materialCategory.setCategoryRank(categoryRank);
                }
                materialCategory.setUpdateUserId(userId);
                this.baseMapper.update(materialCategory, queryWrapper);
            }
            return ResponseResult.success().add("materialCategoryList", materialCategoryMapper.getMaterialCategoryDtlList());
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error().add("请求失败", e.getMessage());
        }
    }

    ResponseResult checkUpdate(List<CategoryUpdateDTO> categoryUpdateDTOList){
        if (categoryUpdateDTOList == null || categoryUpdateDTOList.size() == 0){
            return ResponseResult.error("请求参数不能为空");
        }
        for (CategoryUpdateDTO categoryUpdateDTO : categoryUpdateDTOList){
            Integer categoryId = categoryUpdateDTO.getCategoryId();
            if (categoryId == null){
                return ResponseResult.error("请求更新目录分类编码不能为空");
            }
            MaterialCategory materialCategory = this.baseMapper.selectOne(new QueryWrapper<MaterialCategory>().eq("CATEGORY_ID", categoryId));
            if (materialCategory == null){
                return ResponseResult.error("请求更新目录分类编码" + categoryId + "不存在");
            }
        }
        return ResponseResult.success();
    }

    /** 停用或启用 请购商城目录分类数据，isDeleted = 1 删除，isDeleted = 0 启用； */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized ResponseResult deleteCategory(Integer categoryId, String isDeleted, String userId) {
        try {
            if (categoryId == null){
                return ResponseResult.error("请求目录编号不能为空");
            }
            QueryWrapper<MaterialCategory> queryWrapper = new QueryWrapper<MaterialCategory>().eq("CATEGORY_ID", categoryId);
            MaterialCategory materialCategory = this.baseMapper.selectOne(queryWrapper);
            if (materialCategory == null){
                return ResponseResult.error("请求更新目录分类编码" + categoryId + "不存在");
            }
            if ("0".equals(isDeleted)){
                materialCategory.setIsDeleted(isDeleted);
                materialCategory.setUpdateUserId(userId);
                this.baseMapper.update(materialCategory, queryWrapper);
                return ResponseResult.success("目录编号" + categoryId + "已启用").add("materialCategoryList", materialCategoryMapper.getMaterialCategoryDtlList());
            } else if ("1".equals(isDeleted)){
                materialCategory.setIsDeleted(isDeleted);
                materialCategory.setUpdateUserId(userId);
                this.baseMapper.update(materialCategory, queryWrapper);
                return ResponseResult.success("目录编号" + categoryId + "已停用").add("materialCategoryList", materialCategoryMapper.getMaterialCategoryDtlList());
            } else {
                return ResponseResult.error("请求参数值 isDeleted " + isDeleted + "非法");
            }
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error().add("请求失败", e.getMessage());
        }
    }

    /** 获取停用目录信息 */
    @Override
    public ResponseResult getDeletedCategory() {
        return ResponseResult.success().add("materialCategoryList", materialCategoryMapper.getDeletedCategory());
    }
}
